<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="区域名称">
              <a-input placeholder="请输入区域名称" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('区域管理')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :expandedRowKeys="expandedRowKeys"
        @change="handleTableChange"
        @expand="handleExpand"
        v-bind="tableProps">

        <template slot="status" slot-scope="text">
          <a-tag v-if="text==1" color="green">正常</a-tag>
          <a-tag v-if="text==0" color="red">错误</a-tag>
        </template>
        <template slot="imgFlag" slot-scope="text,record,index">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img  v-else @click='imgClickView(text)' :src='getImgView(text)' height='25px'
                alt='' style='max-width:80px;font-size: 12px;font-style: italic;cursor: pointer;' />
          <!--多图片点击预览组件-->
          <duo-image-viewer :list="imgSrcList"
                            @update:show="handleClose"
                            :show="showViewer" :currentIndex="currentIndex"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>


        <span slot="action" slot-scope="text,record">
          <a @click="handleAddChild(record)">添加子区域</a>
          <a-divider type="vertical" />
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
           <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteNode(record)">
                  <a>删除</a>
                </a-popconfirm>
          <a-divider type="vertical" />
<!--          <a @click="initMap">查看平面图</a>-->

    <a @click="initMap">查看平面图</a>

   <a-modal id="mod" width="1000px"  v-model="visible" title="平面图" :bodyStyle="{height:'600px'}" >
<!--        <div style="width: 900px;height: 600px">-->
             <div id="map">
             </div>
<!--        </div>-->
  </a-modal>
        </span>
      </a-table>
    </div>
    <bsMapArea-modal ref="modalForm" @ok="modalFormOk"></bsMapArea-modal>
  </a-card>
</template>
<style scoped>
#map {
  width: 100%;
  height: 100%;
  border: 1px solid #ccc;
  margin-bottom: 10px;
}

</style>
<script>

  import { getAction, deleteAction } from '@/api/manage'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import BsMapAreaModal from './modules/BsMapAreaModal'
  import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import { filterObj } from '@/utils/util';
  import L from "leaflet";
  import 'leaflet/dist/leaflet.css';
  import 'leaflet.pm';
  import 'leaflet.pm/dist/leaflet.pm.css';

  export default {
    name: "BsMapAreaList",
    mixins:[JeecgListMixin],
    components: {
      BsMapAreaModal,
    },
    data () {
      return {
        map:'',
        visible: false,
        /*** 多图片查看 start*/
        currentIndex: 0, // 打开图片查看器时，需要定位到的图片的索引
        imgSrcList: [], // 图片查看器数据集
        showViewer: false, // 是否打开图片查看器
        description: '区域管理管理页面',
        // 表头
        columns: [
          {
            title:'区域名称',
            align:"left",
            dataIndex: 'name'
          },
          {
            title:'地图编码',
            align:"left",
            dataIndex: 'mapCode'
          },
          {
            title:'排序',
            align:"left",
            dataIndex: 'sort'
          },
          {
            title:'联系电话',
            align:"left",
            dataIndex: 'phone'
          },
          {
            title:'备注',
            align:"left",
            dataIndex: 'description'
          },
          {
            title:'平面图',
            align:"left",
            dataIndex: 'imgUrl',
            scopedSlots: {customRender: 'imgFlag'}
          },
          // {
          //   title:'坐标(所在位置)',
          //   align:"left",
          //   dataIndex: 'atLocation'
          // },
          {
            title:'状态',
            align:"left",
            dataIndex: 'status',
            scopedSlots: {customRender: 'status'}
          },
          // {
          //   title:'创建日期',
          //   align:"left",
          //   dataIndex: 'createTime',
          //   customRender:function (text) {
          //     return !text?"":(text.length>10?text.substr(0,10):text)
          //   }
          // },
          // {
          //   title:'更新日期',
          //   align:"left",
          //   dataIndex: 'updateTime',
          //   customRender:function (text) {
          //     return !text?"":(text.length>10?text.substr(0,10):text)
          //   }
          // },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            scopedSlots: { customRender: 'action' },
          }
        ],
        url: {
          list: "/regional/bsMapArea/rootList",
          childList: "/regional/bsMapArea/childList",
          getChildListBatch: "/regional/bsMapArea/getChildListBatch",
          delete: "/regional/bsMapArea/delete",
          deleteBatch: "/regional/bsMapArea/deleteBatch",
          exportXlsUrl: "/regional/bsMapArea/exportXls",
          importExcelUrl: "regional/bsMapArea/importExcel",
        },
        expandedRowKeys:[],
        hasChildrenField:"hasChild",
        pidField:"parentId",
        dictOptions: {},
        loadParent: false
      }
    },
    computed: {
      importExcelUrl(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
      tableProps() {
        let _this = this
        return {
          // 列表项是否可选择
          rowSelection: {
            selectedRowKeys: _this.selectedRowKeys,
            onChange: (selectedRowKeys) => _this.selectedRowKeys = selectedRowKeys
          }
        }
      }
    },
    methods: {
      imgClickView(text){
        // 将图片路径处理一下
        let srcArray = text.split(",")
        let srcAllArray= []
        srcArray.forEach((temp)=>{
          srcAllArray.push(this.getImgView(temp))
        })
        this.imgSrcList = srcAllArray;
        this.showViewer = !this.showViewer
      },
      // // 多图片查看器打开
      handleOpen() {
        this.showViewer = !this.showViewer
      },
      // 多图片查看器关闭
      handleClose() {
        this.showViewer = false
      },
      getImgView(text){
        if(text && text.indexOf(",")>0){
          text = text.substring(0,text.indexOf(","))
        }
        return text;
      },
      initMap(){
        this.visible = true;
        var map=L.map("map",{
          minZoom: 1,
          maxZoom: 4,
          center: [0, 0],
          attributionControl: true,
          zoom: 1,
          crs: L.CRS.Simple
        });
        var w = 4000,
          h = 3000,
          url = 'http://rea1aiaff.hn-bkt.clouddn.com/benbuzongtu.jpg';
        var southWest = map.unproject([0, h], map.getMaxZoom()-1);
        var northEast = map.unproject([w, 0], map.getMaxZoom()-1);
        var bounds = new L.LatLngBounds(southWest, northEast);
        L.imageOverlay(url,bounds).addTo(map);
        map.setMaxBounds(bounds);
      },
      // initMap() {
      //   this.visible = true;
      //   this.map = L.map("map", {
      //     center: [40.02404009136253, 116.50641060224784], // 地图中心
      //     zoom: 14, //缩放比列
      //     zoomControl: true, //禁用 + - 按钮
      //     doubleClickZoom: true, // 禁用双击放大
      //     attributionControl: true // 移除右下角leaflet标识
      //   });
      //   let name = L.tileLayer(
      //     "http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}",
      //   ).addTo(this.map);
      //   //   this.map.removeLayer(name)  // 移除图层
      // },
      loadData(arg){
        if(arg==1){
          this.ipagination.current=1
        }
        this.loading = true
        let params = this.getQueryParams()
        getAction(this.url.list,params).then(res=>{
          if(res.success){
            let result = res.result
            if(Number(result.total)>0){
              this.ipagination.total = Number(result.total)
              this.dataSource = this.getDataByResult(res.result.records)
              return this.loadDataByExpandedRows(this.dataSource)
            }else{
              this.ipagination.total=0
              this.dataSource=[]
            }
          }else{
            this.$message.warning(res.message)
          }
        }).finally(()=>{
          this.loading = false
        })
      },
      // 根据已展开的行查询数据（用于保存后刷新时异步加载子级的数据）
      loadDataByExpandedRows(dataList) {
        if (this.expandedRowKeys.length > 0) {
          return getAction(this.url.getChildListBatch,{ parentIds: this.expandedRowKeys.join(',') }).then(res=>{
            if (res.success && res.result.records.length>0) {
              //已展开的数据批量子节点
              let records = res.result.records
              const listMap = new Map();
              for (let item of records) {
                let pid = item.pid;
                if (this.expandedRowKeys.join(',').includes(pid)) {
                 let mapList = listMap.get(pid);
                  if (mapList == null) {
                    mapList = [];
                  }
                  mapList.push(item);
                  listMap.set(pid, mapList);
                }
              }
              let childrenMap = listMap;
              let fn = (list) => {
                list.forEach(data => {
                  if (this.expandedRowKeys.includes(data.id)) {
                    data.children = this.getDataByResult(childrenMap.get(data.id))
                    fn(data.children)
                  }
                })
              }
              fn(dataList)
            }
          })
        } else {
          return Promise.resolve()
        }
      },
      getQueryParams(arg) {
        //获取查询条件
        let sqp = {}
        let param = {}
        if(this.superQueryParams){
          sqp['superQueryParams']=encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        if(arg){
          param = Object.assign(sqp, this.isorter ,this.filters);
        }else{
          param = Object.assign(sqp, this.queryParam, this.isorter ,this.filters);
        }
        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        return filterObj(param);
      },
      searchReset() {
        //重置
        this.expandedRowKeys = []
        this.queryParam = {}
        this.loadData(1);
      },
      getDataByResult(result){
        if(result){
          return result.map(item=>{
            //判断是否标记了带有子节点
            if(item[this.hasChildrenField]=='1'){
              let loadChild = { id: item.id+'_loadChild', name: 'loading...', isLoading: true }
              item.children = [loadChild]
            }
            return item
          })
        }
      },
      handleExpand(expanded, record){
        // 判断是否是展开状态
        if (expanded) {
          this.expandedRowKeys.push(record.id)
          if (record.children.length>0 && record.children[0].isLoading === true) {
            let params = this.getQueryParams();//查询条件
            params[this.pidField] = record.id
            getAction(this.url.childList,params).then((res)=>{
              if(res.success){
                if(res.result.records){
                  record.children = this.getDataByResult(res.result.records)
                  this.dataSource = [...this.dataSource]
                }else{
                  record.children=''
                  record.hasChildrenField='0'
                }
              }else{
                this.$message.warning(res.message)
              }
            })
          }
        }else{
          let keyIndex = this.expandedRowKeys.indexOf(record.id)
          if(keyIndex>=0){
            this.expandedRowKeys.splice(keyIndex, 1);
          }
        }
      },
      handleAddChild(record){
        this.loadParent = true
        let obj = {}
        obj[this.pidField] = record['id']
        this.$refs.modalForm.add(obj);
      },
      handleDeleteNode(record) {
        if(!this.url.delete){
          this.$message.error("请设置url.delete属性!")
          return
        }
        var that = this;
        deleteAction(that.url.delete, {id: record.id}).then((res) => {
          if (res.success) {
             that.loadData(1)
          } else {
            that.$message.warning(res.message);
          }
        });
      }

    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>